//编写一段代码，不使用临时变量交换a和b的值

/**
    第一种方法：
        用a保存，a和b的差，即a' = a-b
        这时b要等于原来的a，b' = b+(a-b) = b+a'
        这时的a要等于原来的b，a = b+(a-b)-(a-b) = b=b'-a'

    第二种方法：
        主要知道两个公式：
            (1) 相同数的异或 = 0
            (2) 0和任何数的异或 = 数本身
        b = a^a^b,b = b^b^a  //并且异或也符合交换率，b = a^b^a

        //交换方式
        a' = a^b;
        b' = b^b^a=b^a'
        a = a^a^b = b^a'^a'=b'^a'
*/

#if 1

#include <iostream>

void swap1(int &a,int &b)
{
    a = a-b;
    b = b+a;
    a = b-a;
}

void swap2(int &a,int &b)
{

    a = a^b;
    b = a^b;
    a = a^b;
}
using namespace std;

int main()
{

    //通过计算进行交换
    int a = 3,b=4;
    cout << "交换前：a = "<<a<<",b = "<<b<<endl;
    swap1(a,b);
    cout << "交换后：a = "<<a<<",b = "<<b<<endl;

    //通过位运算进行交换
    a = 5,b=6;
    cout << "交换前：a = "<<a<<",b = "<<b<<endl;
    swap2(a,b);
    cout << "交换后：a = "<<a<<",b = "<<b<<endl;
	system("pause");
	return 0;
}
#endif
